package com.sihan.framework.etm.controller;

import com.framework.annotation.BusinessLog;
import com.framework.annotation.ParamParser;
import com.framework.model.ApiResult;
import com.framework.model.PageResult;
import com.sihan.framework.etm.service.SessionService;
import com.sihan.framework.etm.vo.SessionVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "会话管理")
@RestController
@RequestMapping("/system/v0/session")
public class AdminSessionController {

  @Autowired
  private SessionService sessionService;

  @ApiOperation("查询在线用户列表")
  @GetMapping("/sessions")
  @BusinessLog(value = "查询在线用户列表")
  @RequiresPermissions("sys:monitor:session:view")
  public ApiResult<?> selectSessions() {
    List<SessionVO> data = sessionService.selectSessions();
    PageResult<SessionVO> result = new PageResult<>();
    result.setData(data);
    result.setTotalCount(data.size());
    result.setPageSize(data.size());
    result.setPageNum(1);
    return ApiResult.success(result);
  }

  @ApiOperation("踢出用户")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "sessionId", value = "sessionId", dataType = "String", paramType = "form")
  })
  @PostMapping("/delete")
  @BusinessLog("踢除用户")
  @RequiresPermissions("sys:monitor:session:delete")
  public ApiResult<?> deleteSession(String sessionIds, @ParamParser String usernames) {
    Session currentSession = SecurityUtils.getSubject().getSession();
    String[] sessionIdsArray = sessionIds.split(",");
    for (String sessionId : sessionIdsArray) {
      if (currentSession.getId().equals(sessionId)) {
        return ApiResult.fail("不能剔除自己");
      }
    }

    for (String sessionId : sessionIdsArray) {
        sessionService.delete(sessionId);
    }
    return ApiResult.success();
  }

}
